<template>
  <div class="vulnerability-detection">
    <!-- 页面标题 -->
    <h2 class="vulnerability-title">漏洞检测</h2>

    <!-- 搜索框 -->
    <div class="search-section" style="display: flex; gap: 10px; align-items: center;">
      <el-select v-model="selectedPlatform" placeholder="选择平台" @change="filterVulnerabilities">
        <el-option label="全部平台" value="all" />
        <el-option label="js-evm" value="js-evm" />
        <el-option label="Py-EVM" value="py-evm" />
        <el-option label="Aleth" value="aleth" />
        <el-option label="Geth" value="geth" />
      </el-select>
      <el-input v-model="searchVulnerability" placeholder="漏洞名" style="max-width: 200px;" />
      <el-button type="primary" @click="searchVulnerabilities">查询</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" icon="el-icon-plus" @click="addVulnerability">新增</el-button>
      <el-button type="success" icon="el-icon-download" @click="exportVulnerabilities">导出</el-button>
      <el-button type="warning" icon="el-icon-upload2" @click="importVulnerabilities">导入</el-button>
    </div>

    <!-- 漏洞表格 -->
    <el-table :data="paginatedVulnerabilities" style="width: 100%" stripe>
      <el-table-column prop="name" label="漏洞名" align="center" show-overflow-tooltip />
      <el-table-column prop="platform" label="平台" align="center" show-overflow-tooltip />
      <el-table-column prop="date" label="检测日期" align="center" show-overflow-tooltip />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="viewCaseAnalysis(scope.row)">查看详情</el-button>
          <el-button type="success" size="mini" @click="downloadDetails(scope.row)">下载详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      layout="total, prev, pager, next"
      :total="vulnerabilities.length"
      :page-size="pageSize"
      @current-change="handlePageChange"
    />

    <!-- 案例分析弹窗 -->
    <el-dialog :visible.sync="caseAnalysisVisible" width="60%" title="案例分析">
      <h3>漏洞详情</h3>
      <p><strong>漏洞名:</strong> {{ caseAnalysis.name }}</p>
      <p><strong>平台:</strong> {{ caseAnalysis.platform }}</p>
      <p><strong>描述:</strong> {{ caseAnalysis.description }}</p>
      <p><strong>日志:</strong> {{ caseAnalysis.crashLog }}</p>
      <p><strong>操作码执行跟踪:</strong></p>
      <el-table :data="caseAnalysis.opcodeTrace" style="width: 100%">
        <el-table-column prop="step" label="执行步骤" />
        <el-table-column prop="opcode" label="操作码" />
        <el-table-column prop="description" label="描述" />
      </el-table>
      <p><strong>根因分析:</strong> {{ caseAnalysis.rootCause }}</p>

      <span slot="footer" class="dialog-footer">
        <el-button @click="caseAnalysisVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 新增漏洞弹窗 -->
    <el-dialog :visible.sync="addVulnerabilityVisible" width="60%" title="新增漏洞">
      <el-form :model="newVulnerability" label-width="120px">
        <el-form-item label="漏洞名">
          <el-input v-model="newVulnerability.name" />
        </el-form-item>
        <el-form-item label="平台">
          <el-select v-model="newVulnerability.platform">
            <el-option label="js-evm" value="js-evm" />
            <el-option label="Py-EVM" value="py-evm" />
            <el-option label="Aleth" value="aleth" />
            <el-option label="Geth" value="geth" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="newVulnerability.description" type="textarea" />
        </el-form-item>
        <el-form-item label="崩溃日志">
          <el-input v-model="newVulnerability.crashLog" type="textarea" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVulnerabilityVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNewVulnerability">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchPlatform: '',
      searchVulnerability: '',
      selectedPlatform: 'all', // 默认显示所有平台
      vulnerabilities: [
        { name: 'PY-EVM漏洞', platform: 'py-evm', description: '误报', date: '2024-10-17', status: 'CLOSED', crashLog: `Traceback (most recent call last):
  File "/path/to/evm/evm.py", line 200, in execute
    self.create_contract()
  File "/path/to/evm/evm.py", line 150, in create_contract
    raise Exception("BASEFEE value mismatch detected")
Exception: BASEFEE value mismatch detected
`, opcodeTrace: [{ step: 1, opcode: 'BASEFEE', description: '获取区块的基础费用' }, { step: 2, opcode: 'PUSH1', description: '将值0推入栈' }, { step: 3, opcode: 'MSTORE', description: '将栈顶的值存入内存' },
          { step: 4, opcode: 'PUSH1', description: '将值40推入栈' }, { step: 5, opcode: 'PUSH1', description: '将值0推入栈' }, { step: 6, opcode: 'RETURN', description: '返回内存中的数据' }], rootCause: 'BASEFEE操作码未能使用genesis.json中指定的baseFeePerGas值，导致返回值不正确。' },
        { name: 'EthereumJS漏洞', platform: 'js-evm', description: '建议使用ethereum-vm', date: '2024-10-17', status: 'CLOSED' },
        { name: 'SealEVM漏洞', platform: 'seal-evm', description: '开发者提到会修复，增加gas setting', date: '2024-10-17', status: 'CLOSED' },
        { name: 'PY-EVM漏洞', platform: 'py-evm', description: '开发者无法复现', date: '2024-10-17', status: 'CLOSED' },
        { name: 'Geth误报', platform: 'geth', description: '确认为Geth/genesis.json错误配置导致的误报', date: '2024-10-17', status: 'CLOSED' },
        { name: 'PY-EVM漏洞修复', platform: 'py-evm', description: '开发者已经修复，建议测试新版本', date: '2024-10-17', status: '已修复' },
        { name: 'Geth漏洞修复', platform: 'geth', description: '开发者已经给出补丁PR', date: '2024-10-17', status: '已修复' },
        { name: 'SealEVM漏洞', platform: 'seal-evm', description: '操作码CREATE2的栈深度定义错误，存在栈溢出问题，开发者已采用PR', date: '2024-10-18', status: '已修复' },
        { name: '长安链VM-evm漏洞', platform: 'chainmaker', description: '来自SealEVM的问题，长安链开发者称会修复', date: '2024-10-18', status: '计划修复' },
        { name: 'SealEVM漏洞', platform: 'seal-evm', description: '执行的字节码不以结束操作码结尾时出现数组越界错误，导致无法正确返回消耗的gas值，当前执行消耗了所有提供的gas', date: '2024-10-18', status: '已修复' },
        { name: 'SealEVM漏洞', platform: 'seal-evm', description: 'msize可能输出结果不是32的整数倍，已提交PR帮助开发者修复，开发者已经修复', date: '2024-07-27', status: '已修复' },
        { name: 'execution-specs漏洞', platform: 'execution-specs', description: 'msize可能输出结果不是32的整数倍', date: '2024-10-17', status: '已修复' },
        { name: '长安链VM-evm漏洞', platform: 'chainmaker', description: '来自SealEVM的问题，数组越界', date: '2024-10-18', status: '计划修复' },
        { name: 'Geth漏洞修复', platform: 'geth', description: 'evm中sender地址的账户被覆写，导致执行BALANCE的返回值错误', date: '2024-08-01', status: '已修复' },
        { name: 'SealEVM漏洞', platform: 'seal-evm', description: '对不存在的账户的code未返回0，返回了error', date: '2024-10-18', status: '已修复' },
        { name: 'EthereumJS漏洞', platform: 'js-evm', description: '内存扩展行为不同，计划修复', date: '2024-08-06', status: '计划修复' },
        { name: 'Besu漏洞修复', platform: 'besu', description: 'Besu-docker version entrypoint broken', date: '2024-10-18', status: '已修复' },
        { name: 'Besu漏洞修复', platform: 'besu', description: 'besu对gasLimit的设置失效', date: '2024-10-18', status: '已修复' },
        { name: 'Besu漏洞修复', platform: 'besu', description: 'besu执行操作码basefee时暂停后续操作码的执行，原因是genesis必须设置baseFeePerGas', date: '2024-08-07', status: '已修复' },
        { name: 'Geth漏洞修复', platform: 'geth', description: '执行操作码basefee返回值不正确，未采用genesis中设置的值', date: '2024-08-08', status: '已修复', crashLog: `Traceback (most recent call last):
  File "/path/to/evm/evm.py", line 200, in execute
    self.create_contract()
  File "/path/to/evm/evm.py", line 150, in create_contract
    raise Exception("BASEFEE value mismatch detected")
Exception: BASEFEE value mismatch detected
`, opcodeTrace: [{ step: 1, opcode: 'BASEFEE', description: '获取区块的基础费用' }, { step: 2, opcode: 'PUSH1', description: '将值0推入栈' }, { step: 3, opcode: 'MSTORE', description: '将栈顶的值存入内存' },
          { step: 4, opcode: 'PUSH1', description: '将值40推入栈' }, { step: 5, opcode: 'PUSH1', description: '将值0推入栈' }, { step: 6, opcode: 'RETURN', description: '返回内存中的数据' }], rootCause: 'BASEFEE操作码未能使用genesis.json中指定的baseFeePerGas值，导致返回值不正确。' },
        { name: 'revm漏洞', platform: 'revm', description: 'gasUsed显著高于其他EVM', date: '2024-08-13', status: '未修复' },
        { name: 'revm漏洞', platform: 'revm', description: '合约部署地址不支持自定义，部署在0 address导致了dalegatecall的循环调用', date: '2024-08-14', status: '未修复' },
        { name: 'execution-specs漏洞', platform: 'execution-specs', description: '规范对函数process_message功能的描述错误', date: '2024-08-20', status: '未修复' },
        { name: 'SealEVM漏洞', platform: 'seal-evm', description: '数学操作对边界值处理存在问题', date: '2024-08-23', status: '已修复' },
        { name: '长安链VM-evm漏洞', platform: 'chainmaker', description: 'SealEVM的问题，开发者称会尽快修复', date: '2024-09-02', status: '计划修复' },
        { name: 'Besu漏洞', platform: 'besu', description: '没有REVERT原因时错误输出，开发者已经修复', date: '2024-09-12', status: '计划修复' },
        { name: 'Nethermind漏洞', platform: 'nethermind', description: '无法执行shanghai分叉引入的操作码（如PUSH0）', date: '2024-10-18', status: 'OPEN' },
        {
          name: 'CVE-2024-19184',
          platform: 'py-evm',
          description: 'Py-EVM在处理合约创建时存在竞争条件。',
          date: '2024-10-18',
          status: '已修复',
          crashLog: `Traceback (most recent call last):
  File "/path/to/evm/evm.py", line 200, in execute
    self.create_contract()
  File "/path/to/evm/evm.py", line 150, in create_contract
    raise Exception("Race condition detected")
Exception: Race condition detected
`,
          opcodeTrace: [
            { step: 1, opcode: 'CREATE', description: '创建新合约' },
            { step: 2, opcode: 'SSTORE', description: '存储数据' },
            { step: 3, opcode: 'REVERT', description: '回滚操作' }
          ],
          rootCause: '线程竞态条件导致合约执行失败。',
          fixStatus: '已修复',
          fixProgress: 100,
          fixLog: [
            { commit: '修复提交#1', date: '2024-10-19' }
          ]
        },
        {
          name: 'CVE-2024-19184',
          platform: 'py-evm',
          description: 'Py-EVM在处理合约创建时存在竞争条件。',
          date: '2024-10-18',
          status: '已修复',
          crashLog: `Traceback (most recent call last):
  File "/path/to/evm/evm.py", line 200, in execute
    self.create_contract()
  File "/path/to/evm/evm.py", line 150, in create_contract
    raise Exception("Race condition detected")
Exception: Race condition detected
`,
          opcodeTrace: [
            { step: 1, opcode: 'CREATE', description: '创建新合约' },
            { step: 2, opcode: 'SSTORE', description: '存储数据' },
            { step: 3, opcode: 'REVERT', description: '回滚操作' }
          ],
          rootCause: '线程竞态条件导致合约执行失败。',
          fixStatus: '已修复',
          fixProgress: 100,
          fixLog: [
            { commit: '修复提交#1', date: '2024-10-19' }
          ]
        },
        {
          name: 'CVE-2024-19184',
          platform: 'py-evm',
          description: 'Py-EVM在处理合约创建时存在竞争条件。',
          date: '2024-10-18',
          status: '已修复',
          crashLog: `Traceback (most recent call last):
  File "/path/to/evm/evm.py", line 200, in execute
    self.create_contract()
  File "/path/to/evm/evm.py", line 150, in create_contract
    raise Exception("Race condition detected")
Exception: Race condition detected
`,
          opcodeTrace: [
            { step: 1, opcode: 'CREATE', description: '创建新合约' },
            { step: 2, opcode: 'SSTORE', description: '存储数据' },
            { step: 3, opcode: 'REVERT', description: '回滚操作' }
          ],
          rootCause: '线程竞态条件导致合约执行失败。',
          fixStatus: '已修复',
          fixProgress: 100,
          fixLog: [
            { commit: '修复提交#1', date: '2024-10-19' }
          ]
        },
        {
          name: 'CVE-2024-19184',
          platform: 'py-evm',
          description: 'Py-EVM在处理合约创建时存在竞争条件。',
          date: '2024-10-18',
          status: '已修复',
          crashLog: `Traceback (most recent call last):
  File "/path/to/evm/evm.py", line 200, in execute
    self.create_contract()
  File "/path/to/evm/evm.py", line 150, in create_contract
    raise Exception("Race condition detected")
Exception: Race condition detected
`,
          opcodeTrace: [
            { step: 1, opcode: 'CREATE', description: '创建新合约' },
            { step: 2, opcode: 'SSTORE', description: '存储数据' },
            { step: 3, opcode: 'REVERT', description: '回滚操作' }
          ],
          rootCause: '线程竞态条件导致合约执行失败。',
          fixStatus: '已修复',
          fixProgress: 100,
          fixLog: [
            { commit: '修复提交#1', date: '2024-10-19' }
          ]
        },
        {
          name: 'CVE-2024-19184',
          platform: 'py-evm',
          description: 'Py-EVM在处理合约创建时存在竞争条件。',
          date: '2024-10-18',
          status: '已修复',
          crashLog: `Traceback (most recent call last):
  File "/path/to/evm/evm.py", line 200, in execute
    self.create_contract()
  File "/path/to/evm/evm.py", line 150, in create_contract
    raise Exception("Race condition detected")
Exception: Race condition detected
`,
          opcodeTrace: [
            { step: 1, opcode: 'CREATE', description: '创建新合约' },
            { step: 2, opcode: 'SSTORE', description: '存储数据' },
            { step: 3, opcode: 'REVERT', description: '回滚操作' }
          ],
          rootCause: '线程竞态条件导致合约执行失败。',
          fixStatus: '已修复',
          fixProgress: 100,
          fixLog: [
            { commit: '修复提交#1', date: '2024-10-19' }
          ]
        }

      ],
      filteredVulnerabilities: [],
      caseAnalysisVisible: false,
      addVulnerabilityVisible: false,
      caseAnalysis: {},
      newVulnerability: {
        name: '',
        platform: '',
        description: '',
        crashLog: ''
      },
      currentPage: 1,
      pageSize: 10
    }
  },
  computed: {
    paginatedVulnerabilities() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredVulnerabilities.slice(start, end)
    }
  },
  mounted() {
    this.filterVulnerabilities() // 初始化过滤器
  },
  methods: {
    // 根据搜索条件筛选漏洞
    addVulnerability() {
      this.caseAnalysis = {
        name: '',
        platform: '',
        description: '',
        date: '',
        status: '',
        crashLog: '',
        opcodeTrace: [],
        rootCause: '',
        fixStatus: '',
        fixProgress: 0,
        fixLog: []
      }
      this.caseAnalysisVisible = true
    },
    // 过滤漏洞
    filterVulnerabilities() {
      this.filteredVulnerabilities = this.vulnerabilities
    },
    searchVulnerabilities() {
      this.filteredVulnerabilities = this.vulnerabilities.filter((vuln) => {
        return (
          (this.searchPlatform === '' || vuln.platform.includes(this.searchPlatform)) &&
          (this.searchVulnerability === '' || vuln.name.includes(this.searchVulnerability))
        )
      })
    },
    // 重置搜索条件
    resetSearch() {
      this.searchPlatform = ''
      this.searchVulnerability = ''
      this.filterVulnerabilities()
    },
    // 新增漏洞
    addVulnerability() {
      this.newVulnerability = { name: '', platform: '', description: '', crashLog: '' }
      this.addVulnerabilityVisible = true
    },
    // 初始化过滤器
    filterVulnerabilities() {
      this.filteredVulnerabilities = this.vulnerabilities
    },
    // 查看详细案例分析
    viewCaseAnalysis(vulnerability) {
      this.caseAnalysis = vulnerability
      this.caseAnalysisVisible = true
    },
    // 保存新增漏洞
    saveNewVulnerability() {
      if (this.newVulnerability.name && this.newVulnerability.platform) {
        this.vulnerabilities.push({
          ...this.newVulnerability,
          date: new Date().toISOString().split('T')[0],
          status: '未修复'
        })
        this.addVulnerabilityVisible = false
        this.filterVulnerabilities()
      } else {
        this.$message.error('请填写完整的漏洞信息')
      }
    },
    // 导出漏洞数据
    exportVulnerabilities() {
      const dataStr = JSON.stringify(this.vulnerabilities)
      const blob = new Blob([dataStr], { type: 'application/json' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = 'vulnerabilities.json'
      link.click()
      window.URL.revokeObjectURL(url)
    },
    // 导入漏洞数据
    importVulnerabilities() {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.json'
      input.onchange = (event) => {
        const file = event.target.files[0]
        const reader = new FileReader()
        reader.onload = (e) => {
          try {
            const importedData = JSON.parse(e.target.result)
            this.vulnerabilities = [...this.vulnerabilities, ...importedData]
            this.filterVulnerabilities()
          } catch (error) {
            this.$message.error('导入文件格式错误')
          }
        }
        reader.readAsText(file)
      }
      input.click()
    },
    // 下载单个漏洞详情
    downloadDetails(vulnerability) {
      const dataStr = JSON.stringify(vulnerability)
      const blob = new Blob([dataStr], { type: 'application/json' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `${vulnerability.name}_details.json`
      link.click()
      window.URL.revokeObjectURL(url)
    },
    // 查看详细案例分析
    viewCaseAnalysis(vulnerability) {
      this.caseAnalysis = vulnerability
      this.caseAnalysisVisible = true
    },
    // 分页变更
    handlePageChange(page) {
      this.currentPage = page
    }
  }
}
</script>

<style scoped>
.vulnerability-detection {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.el-table th, .el-table td {
  /* border-right: 1px solid #dcdfe6; */
  border: 1px solid #dcdfe6;
  margin-top: 20px;
}

.vulnerability-title {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 20px;
}
</style>
